package com.chj.web;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chj.constants.Constants;
import com.chj.entity.ECar;
import com.chj.entity.ECarDataGridJson;
import com.chj.entity.Message;
import com.chj.entity.MessageDataGridJson;
import com.chj.entity.NetWork;
import com.chj.entity.NetWorkDataGridJson;
import com.chj.entity.Order;
import com.chj.entity.OrderDataGridJson;
import com.chj.entity.Park;
import com.chj.entity.ParkDataGridJson;
import com.chj.entity.ResultModel;
import com.chj.entity.User;
import com.chj.entity.UserDataGridJson;
import com.chj.service.ECarService;
import com.chj.service.MessageService;
import com.chj.service.NetWorkServcie;
import com.chj.service.OrderService;
import com.chj.service.ParkService;
import com.chj.service.UserService;
import com.chj.util.JSONUtils;


@Controller
@RequestMapping("admin")
public class AdmainController {

    @Resource
    private UserService  userService;

    @Resource
    private NetWorkServcie netWorkService;

    @Resource
    private OrderService orderService;

    @Resource
    private ParkService parkService;

    @Resource
    private ECarService eCarService;

    @Resource
    private MessageService messageService;

    @RequestMapping(value="index")
    public String adminIndex(){
        return "admin/index";
    }

    //String
    @RequestMapping(value="login")
    public ModelAndView adminLogin(){

        return new ModelAndView("admin/login",null);
    }

    @RequestMapping(value="login_submit")
    public ModelAndView loginSubmit(String adminName
                                  , String adminPassword
                                  , HttpServletRequest request){
        if (request.getSession().getAttribute(Constants.LOGIN_AMDIN) != null) {
            return new ModelAndView("admin/index", null);
        }

        User admin = userService.getAdmin(adminName, adminPassword);
        HttpSession session = request.getSession();
        if (admin != null) {
            session.setAttribute(Constants.LOGIN_AMDIN, admin);
            return new ModelAndView("admin/index", null);
        } else {
            return new ModelAndView("admin/login", null);
        }
    }

    @RequestMapping(value="add_network")
    public ModelAndView addNetWorkForward(){

        Map<String, Object> map = new HashMap<String, Object>();

        return new ModelAndView("admin/add_network",map);
    }

    @RequestMapping(value="add_network_submit", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addNetWorkSubmit(HttpServletRequest request
                                        ,HttpServletResponse response
                                        ,String netWorkStr
                                        ){

        Map<String, Object> networkMap = JSONUtils.parseJsonStr(netWorkStr);

        String  networkId        = MapUtils.getString(networkMap  ,"networkId");
        String  networkName      = MapUtils.getString(networkMap  ,"networkName");
        Integer networkParkSize  = MapUtils.getIntValue(networkMap  ,"networkParkSize");
        String  networkProvince  = MapUtils.getString(networkMap  ,"networkProvince");
        String  networkCity      = MapUtils.getString(networkMap  ,"networkCity");
        String  networkArea      = MapUtils.getString(networkMap  ,"networkArea");
        String  networkAddress   = MapUtils.getString(networkMap  ,"networkAddress");
        String  networkPrice     = MapUtils.getString(networkMap  ,"networkPrice");
        String  networkTimeBegin = MapUtils.getString(networkMap  ,"networkTimeBegin");
        String  networkTimeEnd   = MapUtils.getString(networkMap  ,"networkTimeEnd");
        Integer networkType      = MapUtils.getInteger(networkMap,"networkType");

        NetWork netWork = new NetWork(networkId
                                    , networkName
                                    , networkParkSize 
                                    , networkProvince
                                    , networkCity
                                    , networkArea
                                    , networkAddress
                                    , NumberUtils.createBigDecimal(networkPrice)
                                    , networkTimeBegin
                                    , networkTimeEnd
                                    , networkType);

        Map<String, Object> map = new HashMap<String, Object>();

        if (netWorkService.checkNetWorkRepeat(netWork)) {

            map.put(Constants.OPERATION_CODE, "0");
            map.put(Constants.ALERT_MESSAGE, "网点名称数据库已经存在请重新输入");
            return map;
        }

        if ( netWorkService.addNetWork(netWork) > 0 ){

            map.put(Constants.OPERATION_CODE, "1");
            map.put(Constants.ALERT_MESSAGE, "添加成功");
        } else {

            map.put(Constants.OPERATION_CODE, "0");
            map.put(Constants.ALERT_MESSAGE, "数据库出现问题添加失败");
        }

        return map;
    }

    @RequestMapping(value="query_network")
    public ModelAndView queryNetwork( HttpServletRequest request
                                    , HttpServletResponse response
                                    , String queryStr){

        Map<String, Object> queryMap = JSONUtils.parseJsonStr(queryStr);

        List<NetWork> netWorkList = netWorkService.getNetWorkListBy(queryMap,0,0);

        Map<String, Object> map = new HashMap<String, Object>();

        map.put("netWorkListSize", netWorkList.size());
        map.put("netWorkList", netWorkList);

        return new ModelAndView("admin/query_network");
    }

    @RequestMapping(value="delete_network")
    public ModelAndView deleteNetwork(){

        Map<String, Object> map = new HashMap<String, Object>();

        return new ModelAndView("admin/delete_network",map);
    }

    @RequestMapping(value="ajax_delete_network")
    @ResponseBody
    public JSONObject ajaxDeleteNetwork(HttpServletRequest request
                                      , HttpServletResponse response
                                      , String networkId){

        JSONObject result = new JSONObject();

        NetWork netWork = new NetWork();
        netWork.setNetworkId(networkId);

        int deleteNetWork = netWorkService.deleteNetWork(netWork);
        if (deleteNetWork > 0) {
            result.put("flg", "true");
        } else {
            result.put("flg", "false");
            result.put("errorMsg", "系统出现问题，请稍后重新尝试");
        }
        return JSONUtils.getJsonObject(result);
    }

    @RequestMapping(value="ajax_delete_park")
    @ResponseBody
    public JSONObject ajaxDeletePark(HttpServletRequest request
                                   , HttpServletResponse response
                                   , String parkId){

        JSONObject result = new JSONObject();

        Park park = parkService.getParkById(parkId);

        int i = parkService.deletePark(park);
        if (i > 0) {
            result.put("flg", "true");
        } else {
            result.put("flg", "false");
            result.put("errorMsg", "系统出现问题，请稍后重新尝试");
        }
        return JSONUtils.getJsonObject(result);
    }

    @RequestMapping(value="delete_msg")
    @ResponseBody
    public JSONObject deleteMsg(HttpServletRequest request
                                   , HttpServletResponse response
                                   , String messageId){

        JSONObject result = new JSONObject();

        int i =  messageService.deleteMsg(messageId);
        if (i > 0) {
            result.put("falg", "true");
        } else {
            result.put("falg", "false");
            result.put("errorMsg", "系统出现问题，请稍后重新尝试");
        }
        return JSONUtils.getJsonObject(result);
    }

    @RequestMapping(value="delete_ecar")
    @ResponseBody
    public JSONObject deleteEcar(HttpServletRequest request
                               , HttpServletResponse response
                               , String ecarPk){

        JSONObject result = new JSONObject();

        int i =  eCarService.deleteECar(ecarPk);
        if (i > 0) {
            result.put("falg", "true");
        } else {
            result.put("falg", "false");
            result.put("errorMsg", "系统出现问题，请稍后重新尝试");
        }
        return JSONUtils.getJsonObject(result);
    }

    @RequestMapping(value="delete_order")
    @ResponseBody
    public JSONObject deleteOrder(HttpServletRequest request
                                , HttpServletResponse response
                                , String orderPk){

        JSONObject result = new JSONObject();

        ResultModel resultModel =  orderService.deleteForOrder(orderPk);
        if (resultModel.getResult() > 0) {
            result.put("falg", "true");
        } else {
            result.put("falg", "false");
            result.put("errorMsg",resultModel.getErrorMsg());
        }
        return JSONUtils.getJsonObject(result);
    }

    @RequestMapping(value="modify_network")
    public ModelAndView modifyNetwork(){

        Map<String, Object> map = new HashMap<String, Object>();

        return new ModelAndView("admin/modify_network",map);
    }
    
    @RequestMapping(value="ajax_modify_network")
    @ResponseBody
    public JSONObject ajaxModifyNetwork(HttpServletRequest                request
                                       ,HttpServletResponse               response
                                       ,@RequestParam("networkId")        String     networkId       
                                       ,@RequestParam("networkName")      String     networkName     
                                       ,@RequestParam("networkParkSize")  Integer    networkParkSize 
                                       ,@RequestParam("networkProvince")  String     networkProvince 
                                       ,@RequestParam("networkCity")      String     networkCity     
                                       ,@RequestParam("networkArea")      String     networkArea     
                                       ,@RequestParam("networkAddress")   String     networkAddress  
                                       ,@RequestParam("networkPrice")     BigDecimal networkPrice    
                                       ,@RequestParam("networkTimeBegin") String     networkTimeBegin
                                       ,@RequestParam("networkTimeEnd")   String     networkTimeEnd ){

        JSONObject result = new JSONObject();

        NetWork netWork = netWorkService.getNetWork(networkId);

        netWork.setNetworkName(networkName);
        netWork.setNetworkParkSize(networkParkSize);
        netWork.setNetworkProvince(networkProvince);
        netWork.setNetworkCity(networkCity);
        netWork.setNetworkArea(networkArea);
        netWork.setNetworkAddress(networkAddress);
        netWork.setNetworkPrice(networkPrice);
        netWork.setNetworkTimeBegin(networkTimeBegin);
        netWork.setNetworkTimeEnd(networkTimeEnd);

        int i = netWorkService.modifyNetWork(networkId,netWork);

        if ( i  > 0) {
            result.put("flg", "true");
        } else {
            result.put("flg", "false");
            result.put("errorMsg", "系统出现问题，请稍后重新尝试");
        }
        return JSONUtils.getJsonObject(result);
    }

    @RequestMapping(value="modify_network_submit")
    public ModelAndView modifyNetworkSubmit(HttpServletRequest                request
                                           ,HttpServletResponse               response
                                           ,@RequestParam("networkId")        String     networkId       
                                           ,@RequestParam("networkName")      String     networkName     
                                           ,@RequestParam("networkParkSize")  Integer    networkParkSize 
                                           ,@RequestParam("networkProvince")  String     networkProvince 
                                           ,@RequestParam("networkCity")      String     networkCity     
                                           ,@RequestParam("networkArea")      String     networkArea     
                                           ,@RequestParam("networkAddress")   String     networkAddress  
                                           ,@RequestParam("networkPrice")     BigDecimal networkPrice    
                                           ,@RequestParam("networkTimeBegin") String     networkTimeBegin
                                           ,@RequestParam("networkTimeEnd")   String     networkTimeEnd  
                                           ,@RequestParam("networkType")      int        networkType     ){

        NetWork netWork = new NetWork(networkId       ,
                                      networkName     ,
                                      networkParkSize ,
                                      networkProvince ,
                                      networkCity     ,
                                      networkArea     ,
                                      networkAddress  ,
                                      networkPrice    ,
                                      networkTimeBegin,
                                      networkTimeEnd  ,
                                      networkType     );

        if (netWorkService.addNetWork(netWork) > 0 ) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }

        Map<String, Object> map = new HashMap<String, Object>();

        map.put("netWork", netWork);

        return new ModelAndView("query_network.do",map);
    }

    @RequestMapping(value = "getNetWorkJson")
    @ResponseBody
    public JSONObject getJson( HttpServletRequest request
                             , HttpServletResponse response
                             , int page
                             , int rows){

        int netWorkListSize = netWorkService.getNetworkListBy(null);
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("networkType",new Integer(1));
        List<NetWork> netWorkList = netWorkService.getNetWorkListBy(queryMap, page, rows);

        NetWorkDataGridJson<NetWork> jsonList = new NetWorkDataGridJson<NetWork>();

        jsonList.setTotal(netWorkListSize);
        jsonList.setRows(netWorkList);

        JSONObject jsonObj = JSONUtils.getJsonObject(jsonList);

        return jsonObj;
    }

    @RequestMapping(value="add_park_manager")
    public ModelAndView addParkManagerForward(){

        Map<String, Object> map = new HashMap<String, Object>();

        return new ModelAndView("admin/add_park_manager",map);
    }

    @RequestMapping(value = "query_park_network")
    public ModelAndView queryParkNetworkForward(){

        Map<String, Object> map = new HashMap<String, Object>();
        return new ModelAndView("admin/query_park_network",map);
    }

    @RequestMapping(value="ajax_modify_park")
    @ResponseBody
    public JSONObject ajaxModifyPark(HttpServletRequest                request
                                       ,HttpServletResponse            response
                                       ,@RequestParam("parkId")        String     parkId
                                       ,@RequestParam("parkName")      String     parkName
                                       ,@RequestParam("parkSize")      String     parkSize
                                       ,@RequestParam("parkPrice")     BigDecimal networkPrice){

        JSONObject result = new JSONObject();

        Park park = parkService.getParkById(parkId);
        park.setParkName(parkName);
        park.setParkSize(parkSize);
        park.setParkPrice(networkPrice);

        int i = parkService.modifyPark(park);

        if ( i  > 0) {
            result.put("flg", "true");
            result.put("errorMsg", "");
        } else {
            result.put("flg", "false");
            result.put("errorMsg", "系统出现问题，请稍后重新尝试");
        }
        return JSONUtils.getJsonObject(result);
    }

    @RequestMapping(value = "query_network_add_park",produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject queryNetworkToAddPark(HttpServletRequest  request
                                 , HttpServletResponse response
                                 , @RequestParam(value="netWorkStr") String netWorkStr) {

        Map<String, Object> queryMap = JSONUtils.parseJsonStr(netWorkStr);

        List<NetWork> netWorkList = netWorkService.getNetWorkListBy(queryMap,0,0);

        Map<String, Object> resultMap = new HashMap<String, Object>();

        resultMap.put("netWorkList", netWorkList);

        return JSONUtils.getJsonObject(resultMap);
    }

    @RequestMapping(value="add_park/{networkId}")
    public ModelAndView addParkManager(@PathVariable("networkId") String netWorkId){

        NetWork netWork = netWorkService.getNetWork(netWorkId);
        List<Park> parks = parkService.getParkListByNetWorkId(netWorkId);

        Map<String, Object> map = new HashMap<String, Object>();

        map.put("netWork", netWork);
        map.put("parks"  , parks);

        return new ModelAndView("admin/park_manager",map);
    }

    
    //通过网点id获取对应的网点信息
    @RequestMapping(value = "getParkByNetworkId/{networkId}", produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject getParkByNetworkId(HttpServletRequest  request
                                       , HttpServletResponse response
                                       , @PathVariable("networkId") String netWorkId
                                       , int page
                                       , int rows) {

        List<Park> sizeList = parkService.getParkListByNetWorkId(netWorkId);
        List<Park> parkList = parkService.getParkListByNetWorkId(netWorkId, page, rows);

        ParkDataGridJson parkDataGridJson = new ParkDataGridJson();

        parkDataGridJson.setPark(parkList);
        parkDataGridJson.setTotal(sizeList.size()+"");

        return JSONUtils.getJsonObject(parkDataGridJson);
    }

    //通过网点id获取对应的网点信息
    @RequestMapping(value = "saveParkByNetWorkId/{networkId}", produces="application/json;charset=UTF-8")
    @ResponseBody
    public JSONObject saveParkByNetWorkId(HttpServletRequest  request
                                        , HttpServletResponse response
                                        , @PathVariable("networkId") String netWorkId
                                        , String parkName
                                        , String parkSize
                                        , String parkPrice) {

        BigDecimal bdecParkPrce = new BigDecimal(parkPrice);

        Park park = new Park(parkName, parkSize, bdecParkPrce, netWorkId);

        NetWork netWork = netWorkService.getNetWork(netWorkId);
        Integer networkParkSize = netWork.getNetworkParkSize();

        List<Park> parkList = parkService.getParkListByNetWorkId(netWorkId);

        Map<String, Object> result = new HashMap<String, Object>();

        if (parkList.size() < networkParkSize) {
            int i = parkService.saveParkWithNetWorkId(netWorkId, park);
            if ( i == 0 ) {
                result.put("errorMsg", "请检查后重新尝试");
            } else {
                result.put("errorMsg", "");
            }
        } else {
            result.put("errorMsg", "追加数量不能超过网点车位数量");
        }

        return JSONUtils.getJsonObject(result);
    }

    @RequestMapping(value="user_manager")
    public String userManager(){
        return "admin/user_manager";
    }

    @RequestMapping(value="order_manager")
    public String orderManager(){
        return "admin/order_manager";
    }

    @RequestMapping(value="ecar_manager")
    public String ecarManager(){
        return "admin/ecar_manager";
    }

    @RequestMapping(value="msg_manager")
    public String msgManager(){
        return "admin/msg_manager";
    }

    //查询用户
    @RequestMapping(value="getUserListBy")
    @ResponseBody
    public JSONObject getUserListBy(HttpServletRequest  request
                                  , HttpServletResponse response
                                  , String queryUserName
                                  , String queryUserPhone
                                  , String queryUserEmail
                                  , String queryRegisterDateFrom
                                  , String queryRegisterDateTo
                                  , int page
                                  , int rows){

        UserDataGridJson userDataGridJson = new UserDataGridJson();

        
        int size = userService.getUserListSizeBy(queryUserName, queryUserPhone, queryUserEmail,queryRegisterDateFrom, queryRegisterDateTo, Constants.USER_TYPE_NORMAL);
        List<User> list = userService.getUserListBy(queryUserName, queryUserPhone, queryUserEmail, queryRegisterDateFrom, queryRegisterDateTo, Constants.USER_TYPE_NORMAL, page, rows);

        userDataGridJson.setTotal(size);
        userDataGridJson.setRows(list);

        return JSONUtils.getJsonObject(userDataGridJson);

    }
    //重置用户密码：
    @RequestMapping(value="reset_user_password")
    @ResponseBody
    public JSONObject resetUserPassword(HttpServletRequest  request
                                      , HttpServletResponse response
                                      , String userPk){

        int i = userService.resetUserPassword(userPk);

        Map<String, Object> result = new HashMap<String, Object>();
        if (i > 0) {
            result.put("falg", "true");
        } else {
            result.put("falg", "false");
            result.put("errorMsg", "系统繁忙，重置失败请稍后再尝试");
        }

        return JSONUtils.getJsonObject(result);
    }

  //查询订单
    @RequestMapping(value="getOrderListBy")
    @ResponseBody
    public JSONObject getOrderListBy(HttpServletRequest  request
                                  , HttpServletResponse response
                                  , String queryOrderId
                                  , String queryUserId
                                  , String queryCreateDateFrom
                                  , String queryCreateDateTo
                                  , int page
                                  , int rows){

        OrderDataGridJson orderDataGridJson = new OrderDataGridJson();

        int size = orderService.getOrderListSizeBy(queryUserId, queryOrderId, queryCreateDateFrom, queryCreateDateTo);
        List<Order> list = orderService.getOrderListBy(queryUserId, queryOrderId, queryCreateDateFrom, queryCreateDateTo, page, rows);

        orderDataGridJson.setTotal(size);
        orderDataGridJson.setRows(list);

        return JSONUtils.getJsonObject(orderDataGridJson);

    }
    
    //查询订单
    @RequestMapping(value="getEcarListBy")
    @ResponseBody
    public JSONObject getEcarListBy(HttpServletRequest  request
                                  , HttpServletResponse response
                                  , String userId
                                  , int page
                                  , int rows){

        ECarDataGridJson eCarDataGridJson = new ECarDataGridJson();

        int size = eCarService.getECarListSizeBy(userId);
        List<ECar> list = eCarService.getOrderListBy(userId, page, rows);

        eCarDataGridJson.setTotal(size);
        eCarDataGridJson.setRows(list);

        return JSONUtils.getJsonObject(eCarDataGridJson);

    }
    //查询订单
    @RequestMapping(value="getMsgListBy")
    @ResponseBody
    public JSONObject getMsgListBy(HttpServletRequest  request
                                  , HttpServletResponse response
                                  , String userId
                                  , String createDateFrom
                                  , String createDateTo
                                  , int page
                                  , int rows){

        MessageDataGridJson<Message> messageDataGridJson = new MessageDataGridJson<Message>();

        int size = messageService.getMsgListBy(userId,createDateFrom,createDateTo);
        List<Message> list = messageService.getMsgListBy(userId,createDateFrom,createDateTo, page, rows);

        messageDataGridJson.setTotal(size);
        messageDataGridJson.setRows(list);

        return JSONUtils.getJsonObject(messageDataGridJson);

    }

    //修改管理员密码：
    @RequestMapping(value="admin_change_password")
    @ResponseBody
    public String change_admin_password(HttpServletRequest  request
                                      , HttpServletResponse response
                                      , String userPassword){

        User admin = (User)request.getSession().getAttribute(Constants.LOGIN_AMDIN);

        admin.setUserPassword(userPassword);

        int result = userService.changeAdminPassword(admin);

        if (result > 0) {
            request.getSession().setAttribute(Constants.LOGIN_AMDIN, admin);
            return "true";
        } else {
            return "false";
        }
    }

    //管理员后台退出
    @RequestMapping(value="admin_exit")
    public ModelAndView adminExit(HttpServletRequest  request
                                , HttpServletResponse response ){

        HttpSession session = request.getSession();

        session.removeAttribute(Constants.LOGIN_AMDIN);

        return new ModelAndView("admin/login");
    }
}